package android.slc.extras.component.attchment.domain;

import android.slc.extras.component.attchment.entity.Attachment;
import android.slc.extras.component.attchment.utils.AttachmentUtils;
import android.slc.core.vm.SingleLiveEvent;
import android.slc.mp.po.i.IBaseItem;

import androidx.activity.result.ActivityResultCallback;
import androidx.databinding.ObservableBoolean;
import androidx.lifecycle.LiveData;

import com.blankj.utilcode.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.rxjava3.functions.Function;

/**
 * 附件view model
 *
 * @author slc
 * @date 2020-09-08 11:09
 */
public class AttachmentEditVmBox<T extends AttachmentReviewVmBox.AttachmentAdapter> extends AttachmentReviewVmBox<T> {
    public final ActivityResultCallback<List<IBaseItem>> selectAttEventResultCallback = this::onSelectAttResultCallback;
    protected final SingleLiveEvent<Void> selectAttEvent = new SingleLiveEvent<>();
    public final ObservableBoolean showAddBtn = new ObservableBoolean(true);
    private int maxCount = 9;

    public AttachmentEditVmBox() {
    }

    protected void onDataListChangedCallback(List<Attachment> dataList) {
        super.onDataListChangedCallback(dataList);
        showAddBtn.set(dataList.size() < maxCount);
    }

    public void setMaxCount(int maxCount) {
        this.maxCount = maxCount;
    }

    public int getMaxCount() {
        return maxCount;
    }

    public LiveData<Void> getSelectAttEvent() {
        return selectAttEvent;
    }

    /**
     * 选择附件
     */
    public void selectAtt() {
        selectAttEvent.call();
    }

    /**
     * 上传文件
     */
    public io.reactivex.rxjava3.core.Observable<Attachment> uploadAttachment() {
        return getAttachmentAdapter().uploadAttachment();
    }

    /**
     * 添加附件监听
     *
     * @param iBaseItems
     */
    protected void onSelectAttResultCallback(List<IBaseItem> iBaseItems) {
        if (iBaseItems != null) {
            List<Attachment> attachmentList = new ArrayList<>();
            for (IBaseItem iBaseItem : iBaseItems) {
                attachmentList.add(new Attachment(iBaseItem));
            }
            if (!CollectionUtils.isEmpty(attachmentList)) {
                CollectionUtils.forAllDo(attachmentList, (index, item) -> item.setIsAllowEditStatus(AttachmentUtils.IS_ALLOW_EDIT_STATUS_AGREE));
                getDataList().addAll(attachmentList);
                dataListOf.notifyChange();
            }
        }
    }

    @Override
    public void onSucceed(List<Attachment> data) {
        CollectionUtils.forAllDo(data, (index, item) -> item.setIsAllowEditStatus(AttachmentUtils.IS_ALLOW_EDIT_STATUS_AGREE));
        super.onSucceed(data);
    }

    public Function<Attachment, Attachment> refreshAttachment() {
        return attachment -> {
            notifyAttItemDataChangeLd.setValue(attachment);
            return attachment;
        };
    }

}
